const puppeteer = require('puppeteer-core')
const fs = require('fs')
const uuidv1 = require('uuid/v1')

async function getBrowser () {
  return puppeteer.launch({
    headless: false,
    // executablePath: 'D:\\Programs\\chrome-win\\chrome.exe',
    executablePath: 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
    defaultViewport: {
      width: 1920,
      height: 968
    },
    devtools: true,
    userDataDir: './cache/chrome'
  })
}

async function getDefaultPage () {
  const browser = await getBrowser()
  const pages = await browser.pages()
  const page = pages[0]
  return page
}

function uuid () {
  return uuidv1().replace(new RegExp('-', 'gm'), '')
}

function resolveUrlWithOutParams (url) {
  const idx = url.indexOf('?')
  const substr = url.substring(0, idx)
  return substr
}

async function fetch (testUrl) {
  const page = await getDefaultPage()

  const map = {}
  page.on('response', async (resp) => {
    const j = uuid()
    const url = resp.url()
    map[url] = j
    map[resolveUrlWithOutParams(url)] = j

    const buf = await resp.buffer()
    const status = await resp.status()
    const headers = await resp.headers()
    fs.writeFileSync(`./data/${j}.buf`, buf)
    fs.writeFileSync(`./data/${j}.status`, status)
    fs.writeFileSync(`./data/${j}.json`, JSON.stringify(headers))
    // console.log(url)
  })

  await page.goto(testUrl)

  fs.writeFileSync('./data/map.json', JSON.stringify(map))
}

const testUrl = 'https://www.baidu.com/'

async function reappear (testUrl) {
  const page = await getDefaultPage()

  await page.setRequestInterception(true)

  page.on('request', async (req) => {
    const map = require('./data/map.json')
    const url = await req.url()
    const j = map[url] || map[resolveUrlWithOutParams(url)]
    // console.log(url, j)
    const headers = require(`./data/${j}.json`)
    const response = {
      status: parseInt(fs.readFileSync(`./data/${j}.status`).toString()),
      body: fs.readFileSync(`./data/${j}.buf`),
      // body: 'hello',
      headers: JSON.stringify(headers),
      // headers,
      contentType: headers['content-type']
    }
    console.log(response)
    req.respond(response)
  })

  await page.goto(testUrl)
}

async function test () {
  const page = await getDefaultPage()

  await page.setRequestInterception(true)

  page.on('request', async (req) => {
    const url = await req.url()
    console.log(url, testUrl)
    console.log(url === testUrl)
    if (url === testUrl) {
      req.respond({
        status: 200,
        contentType: 'text/html',
        body: fs.readFileSync('./data/0.buf')
      })
    } else {
      req.continue()
    }
  })

  await page.goto(testUrl)
}

// fetch(testUrl)
reappear(testUrl)
// test()

module.exports = {
  fetch,
  reappear,
  test
}
